package com.hkbigdata.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2024-03-06-20:43
 * @see 2194550857@qq.com
 */
public class Flink001_WordCount_Batch {
    public static void main(String[] args) throws Exception {
        //1.准备数源
        //最终效果(spark,1) (kafka,3) (hadoop,2)
        //2.获取flink批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();//alt+enter

        //3.利用环境读取数据源
        DataSource<String> stringDataSource = env.readTextFile("input/word.txt");


        //4.将数据进行扁平化 flatMap map 都属于懒执行算子 =>spark hadoop kafka mysql
        FlatMapOperator<String, String> stringStringFlatMapOperator = stringDataSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
//                System.out.println(value);
                String[] arr = value.split(" ");
                for (int i = 0; i < arr.length; i++) {
//                    System.out.println(arr[i]);
                    out.collect(arr[i]);
                }
            }
        });//ctrl+p查看参数

        //5.将单词映射转换成二元组 (spark,1) (kafka,1) (spark,1) (hadoop,1)
        MapOperator<String, Tuple2<String, Integer>> wordToOne = stringStringFlatMapOperator.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return new Tuple2<>(value, 1);
            }
        });

        //动作的时候才会真正执行
        //wordToOne.print();
        //6.将元组进行分组(hadoop,1) (hadoop,1)
        UnsortedGrouping<Tuple2<String, Integer>> tuple2UnsortedGrouping = wordToOne.groupBy(0);
        //7.聚合
        AggregateOperator<Tuple2<String, Integer>> sum = tuple2UnsortedGrouping.sum(1);

        //8.打印
        sum.print();

    }

}
